import {Product,CProduct} from '../types/product'

interface State{
    list:Product[],    //商品列表
    carList:CProduct[], //购物车列表
    checkAll:boolean    //选中
}

//初始值
let data:State = {
    list:[],
    carList:[],
    checkAll:false  //不是选中状态
}

//查找对应下标  

function getIndex(data:CProduct[],id:number){
    return data.findIndex((item:CProduct) => item.id === id)
}

export default (state=data,action:any) => { //action 对象 type属性
    switch (action.type) {
        case 'INIT_DATA':
            return {...state,list:[...action.list]};
        case 'ADD_PRO':{
            //添加购物车
            // action: target 添加的对象
            //是否添加过
            let target = action.target;
            let index = getIndex(state.carList,target.id);
            
            if(index != -1){
                //已经添加过
                state.carList[index].num++;
            }else{
                //没有添加过
                target.num = 1;       //数量1
                target.checked = true;//选中的状态
                state.carList.push(target);
            }
            console.log(state.carList)
            state.checkAll = state.carList.every((item) => item.checked)
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_NUM':{
            //id:修改对象的id num：修改之后的值  ===》 action.id  action.num
            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.num = action.num;
            console.log("====",target)
            state.carList[index] = {...target};
            return {...state,carList:[...state.carList]}
        }   
        
        case 'DEL_PRO':{
            let index = getIndex(state.carList,action.id);
            state.carList.splice(index,1);
            return {...state,carList:[...state.carList]}
        }
        //切换选中状态
        case 'CHANGE_CHECKED':{
            //id ===> index checked ==》 修改之后的checked

            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.checked = action.checked;

            state.carList[index] = {...target};
            //设置全选全不选
            state.checkAll = state.carList.every((item) => item.checked)
            return {...state,carList:[...state.carList]}
        }
        //切换全选和全不选
        case 'CHANGE_CHEAKALL':{
            //checkAll
            console.log(action.checked)
            state.carList = state.carList.map(item => {
                item.checked = action.checked;
                return {...item}
            })
            state.checkAll = action.checked;
            return {...state,carlist:[...state.carList]}
        }
        default:
            return state;
    }
}